package com.tcu.base.security;

import com.tcu.user.entity.User;
import com.tcu.user.mapper.PermissionMapper;
import com.tcu.user.mapper.RoleMapper;
import com.tcu.user.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class MyRealm extends AuthorizingRealm {

    private UserMapper userMapper;

    private RoleMapper roleMapper;

    private PermissionMapper permissionMapper;
    /**
     * 进行 授权操作
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        User user = (User) principal.getPrimaryPrincipal();
        Set<String> roleNamesByUid = roleMapper.getRoleNamesByUid(user.getId());
        Set<String> permissionNamesByUid = permissionMapper.getPermissionNamesByUid(user.getId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleNamesByUid);
        info.setStringPermissions(permissionNamesByUid);
        return info;
    }

    /**
     * 进行 登录认证 操作
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        User byName = userMapper.findByName(usernamePasswordToken.getUsername());
        User u = userMapper.selectById(byName.getId());
        if (byName==null) {
            throw new UnknownAccountException();
        }
        /**
         * 参数 描述
         * 1，principal
         * 2，加盐后的密码
         * 3，加的盐
         * 4，realm 名称
         */
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(byName,u.getPassword(), ByteSource.Util.bytes(byName.getSalt()),getName());
        return info;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }
    @Autowired
    public void setPermissionMapper(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }
}
